package com.example.interesting.distributed.log.realize.dubbo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: dubbo注册rpc调用过滤器
 * @Author: fyw
 * @Date: 2024/4/6 13:46
 * @History
 */
public class DubboEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private final static String DUBBO_PROPERTY = "dubbo";
    private final static String DUBBO_CONSUMER_FILTER_KEY = "dubbo.consumer.filter";
    private final static String DUBBO_PROVIDER_FILTER_KEY = "dubbo.provider.filter";
    private final static String DUBBO_CONSUMER_FILTER_VAL = "logDubboConsumerFilter";
    private final static String DUBBO_PROVIDER_FILTER_VAL = "logDubboProviderFilter";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        MapPropertySource target = null;
        //获取上下文环境
        MutablePropertySources propertySources = environment.getPropertySources();
        if (propertySources.contains(DUBBO_PROPERTY)) {
            //dubbo 配置
            PropertySource<?> propertySource = propertySources.get(DUBBO_PROPERTY);
            if (propertySource instanceof MapPropertySource) {
                target = (MapPropertySource) propertySource;
                Map<String, Object> source = target.getSource();
                if (!source.containsKey(DUBBO_CONSUMER_FILTER_KEY)) {
                    target.getSource().put(DUBBO_CONSUMER_FILTER_KEY, DUBBO_CONSUMER_FILTER_VAL);
                }
                if (!source.containsKey(DUBBO_PROVIDER_FILTER_KEY)) {
                    target.getSource().put(DUBBO_PROVIDER_FILTER_KEY, DUBBO_PROVIDER_FILTER_VAL);
                }

            }
        }
        if (target == null) {
            Map<String, Object> source = new HashMap<>();
            source.put(DUBBO_CONSUMER_FILTER_KEY,DUBBO_CONSUMER_FILTER_VAL);
            source.put(DUBBO_PROVIDER_FILTER_KEY,DUBBO_PROVIDER_FILTER_VAL);
            target = new MapPropertySource(DUBBO_PROPERTY,source);
        }
        if (!propertySources.contains(DUBBO_PROPERTY)) {
            propertySources.addLast(target);
        }
    }
}
